package cn.tyoui.ssm.controller;

import java.io.File;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import cn.tyoui.ssm.po.ItemsCustom;
import cn.tyoui.ssm.service.interFace.ItemsService;

@Controller
public class ItemsController {

	@Autowired
	private ItemsService itemsService;

	@RequestMapping("/queryItems")
	public String queryItems(Model model) throws Exception {
		List<ItemsCustom> itemsList = itemsService.findItemsList(null);
		model.addAttribute("itemsList", itemsList);
		return "items/itemsList";
	}

	@RequestMapping("/editItems")
	public String editItems(HttpServletRequest request, Model model, Integer id)
			throws Exception {
		ItemsCustom itemsCustom = itemsService.findItemsById(id);
		model.addAttribute("items", itemsCustom);
		request.getSession().setAttribute("items_pic", itemsCustom.getPic());
		return "items/editItems";
	}

	@RequestMapping("/editItemsSubmit")
	public String editItemsSubmit(HttpServletRequest request, Model model,
			Integer id, @Validated ItemsCustom custom, BindingResult result,
			MultipartFile items_pic) throws Exception {
		String pic = (String) request.getSession().getAttribute("items_pic");
		if (result.hasErrors())
			model.addAttribute("listError", result.getAllErrors());
		else {
			String fileName = items_pic.getOriginalFilename();
			if (items_pic != null && fileName != null && fileName.length() > 0) {
				String dir = new File("")+ "\\WebRoot\\pic\\";
				fileName = UUID.randomUUID()
						+ fileName.substring(fileName.lastIndexOf("."));
				File file = new File(dir + fileName);
				items_pic.transferTo(file);
				custom.setPic(fileName);
			}
			
			if (pic != null && custom.getPic() == null)
				custom.setPic(pic);
			itemsService.updateItems(id, custom);
		}
		return "forward:/queryItems.action";
	}
}
